package com.example.demo.config;

import com.example.demo.common.AppConstant;
import com.example.demo.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 拦截用户访问 管理员的接口
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 HttpSession
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConstant.SESSION_USER_KEY);
        if (user.getIsAdmin() == 0) {
            // 是用户， 权限不足
            response.setStatus(403);
//            response.setContentType("text/html;charset=utf8");
//            response.getWriter().write("<h1>用户无法访问，权限不足!<h1>");
            return false;
        }
        return true;
    }
}
